package FormatString;

use strict;
use warnings;

BEGIN {
    use Exporter ();
    our ( $VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS );

    $VERSION = sprintf( "%d", q$Revision$ =~ m{\d+} );
    @ISA     = qw(Exporter);
    @EXPORT  = qw(&format_string
        &unformat_string);
    %EXPORT_TAGS = ();
    @EXPORT_OK   = qw();
} ## end BEGIN

sub format_string($% );
sub unformat_string($% );

sub alt_value($ ) {
    my $value = shift;

    $value =~ s{^\!}{};
    $value =~ s{[^a-zA-Z_0-9-]}{-}g;
    unless ( $value =~ m{^lib}i ) {
        $value =~ s{(?<=.[a-z])(?=[A-Z])}{-}g;
    }
    $value = lc $value;
} ## end sub alt_value($ )

sub format_string($% ) {
    my ( $string, %keys ) = @_;
    return $string unless ( $string =~ m{%} );

    while ( my ( $key, $value ) = each %keys ) {
        my $lckey    = lc $key;
        my $uckey    = uc $key;
        my $altkey   = "alt" . $lckey;
        my $altvalue = alt_value( $value );
        $string =~ s{%$lckey%}{lc $value}ge;
        $string =~ s{%$uckey%}{uc $value}ge;
        $string =~ s{%$altkey%}{$altvalue}ge;
        $string =~ s{%$key%}{$value}gi;
    } ## end while ( my ( $key, $value...))
    return $string;
} ## end sub format_string($% )

sub unformat_string($% ) {
    my ( $string, %keys ) = @_;

    return $string unless defined $string;

    while ( my ( $key, $value ) = each %keys ) {
        my $lcvalue  = lc $value;
        my $ucvalue  = uc $value;
        my $lckey    = lc $key;
        my $uckey    = uc $key;
        my $altkey   = "alt" . $lckey;
        my $altvalue = alt_value( $value );
        if ( $lckey eq $key && $uckey ne $key ) {

            # Fix up key to be mixed cased
            $key =~ s{([[[:lower:]])}{\u$1};
        }

        $string =~ s{$ucvalue}{%$uckey%}g   if ( $ucvalue ne $value );
        $string =~ s{$lcvalue}{%$lckey%}g   if ( $lcvalue ne $value );
        $string =~ s{$altvalue}{%$altkey%}g if ( $lcvalue ne $altvalue );
        $string =~ s{$value}{%$key%}g;
    } ## end while ( my ( $key, $value...))
    return $string;
} ## end sub unformat_string($% )

1;
